<template>
  <div class="app-container">
    <!-- <el-select filterable v-if="!isDetails" v-model="listQuery.type" placeholder="查询模式">
      <el-option v-for="item in menuStatus" :key="item.key" :label="item.display_name" :value="item.key"></el-option>
    </el-select> -->
    <el-date-picker
      v-if="!isDetails"
      v-model="listQuery.start_at"
      type="datetime"
      value-format="yyyy-MM-dd HH:mm:ss"
      placeholder="搜索开始时间"
    ></el-date-picker>
    <el-date-picker
      v-if="!isDetails"
      v-model="listQuery.end_at"
      type="datetime"
      value-format="yyyy-MM-dd HH:mm:ss"
      placeholder="搜索结束时间"
    ></el-date-picker>
    <el-button
      v-if="!isDetails"
      class="mb"
      type="primary"
      @click="getList"
      icon="el-icon-search"
      >搜索
    </el-button>
    <el-button v-if="!isDetails" class="mb" type="primary" @click="getExcel"
      >导出Excel
    </el-button>
    <el-button
      v-if="isDetails"
      class="mb"
      type="primary"
      @click="isDetails = false"
      >退出
    </el-button>
    <el-table
      v-if="!isDetails"
      :data="menuList"
      style="margin-bottom: 20px"
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="add_time" label="时间"></el-table-column>
      <!-- <el-table-column prop="user_id" label="成员ID"> </el-table-column> -->
      <el-table-column prop="user_code" label="成员ID"></el-table-column>
      <el-table-column prop="nickname" label="成员昵称"></el-table-column>
      <el-table-column prop="total_amount" label="流水"></el-table-column>
      <el-table-column min-width="140" label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            plain
          >
            查看详情
          </el-button>
          <!--          <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination
      v-if="!isDetails"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.perPage"
      @pagination="getList"
    />
    <el-table
      v-if="isDetails"
      :data="menuList2"
      style="margin-bottom: 20px"
      row-key="id"
      border
    >
      <!--
         "user_id": 620016,
            "amount": 3000,
            "uid": 567943,
            "hall_id": 12,
            "add_time(送礼时间)": 1601282497,
            "room_id": 3078,
            "give_id": 647539,
            "nickname(收礼者昵称)": "毛里求私",
            "user_code(收礼者id)": 652761,
            "u_nickname(送礼者昵称)": "毛里求斯",
            "u_code(送礼着id)": 305289,
            "gift_id(礼物id)": 151,
            "gift_number(礼物数量)": 10,
            "gift_type(礼物类型)": "送礼物",
         "gift_name(礼物名称)": "草莓", -->

      <el-table-column prop="add_time" label="时间">
        <template slot-scope="scope">
          {{ scope.row.add_time }}
        </template>
      </el-table-column>
      <el-table-column prop="u_code" label="送礼人用户编号"></el-table-column>
      <el-table-column prop="u_nickname" label="送礼人昵称"></el-table-column>
      <el-table-column prop="gift_type" label="礼物类型"></el-table-column>
      <el-table-column prop="gift_name" label="礼物名称"></el-table-column>
      <el-table-column prop="gift_number" label="礼物数量"></el-table-column>
      <el-table-column prop="amount" label="礼物总价值"></el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination
      v-if="isDetails"
      :total="total2"
      :page.sync="listQuery2.pageNum"
      :limit.sync="listQuery2.perPage"
      @pagination="getList2"
    />
    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleDialogClose"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="管理员姓名" prop="admin_account">
          <el-input
            v-model="form.admin_account"
            placeholder="管理员姓名"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="管理员密码" prop="password">
          <el-input v-model="form.password" placeholder="管理员密码" />
        </el-form-item>
        <el-form-item label="厅的号码" prop="sociaty_no">
          <el-input v-model="form.sociaty_no" placeholder="厅的号码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  saveMenu,
  deleteMenu,
  treeMenu,
  updateMenu,
  cacheMenu,
  getExcel
} from "@/api/profit/userWater";
import fileDownload from "js-file-download";
import treeTable from "@/components/TreeTable";
import { validateCh } from "@/utils/validate";
import md5 from "js-md5";
import { getToken } from "@/utils/auth";

const menuTypeOptions = [
  { key: "", display_name: "全部关系" },
  { key: "1", display_name: "直属" },
  { key: "2", display_name: "挂靠" }
];
const menuStatus = [
  { key: "1", display_name: "全部查询模式" },
  { key: "2", display_name: "按天统计" },
  { key: "3", display_name: "按周统计" },
  { key: "4", display_name: "按月统计" }
];

export default {
  components: { treeTable },
  data() {
    const _validateCh = (rule, value, callback) => {
      if (!!value && validateCh(value)) {
        callback(new Error("不能包含中文"));
      }
      callback();
    };
    return {
      expandAll: false,
      // expandAll: true, // 是否全部展开
      expandAllTitle: "展开全部",
      listLoading: true,
      isDetails: false,
      total: 0,
      listQuery: {
        pageNum: 1,
        perPage: 10,
        type: "1",
        start_at: "",
        end_at: ""
      },
      menuList: [],
      total2: 0,
      listQuery2: {
        pageNum: 1,
        perPage: 10,
        user_id: ""
      },
      menuList2: [],
      menuTree: [], // 树形菜单
      dialogFormVisible: false,
      dialogStatus: "",
      titleMap: {
        update: "编辑",
        create: "增加"
      },
      form: {
        admin_account: undefined,
        password: undefined,
        sociaty_no: undefined
      },
      menuTypeOptions,
      menuStatus,
      optionsStatus: [
        { value: undefined, label: "全部状态" },
        { value: "1", label: "正常" },
        { value: "2", label: "封禁" }
      ],
      optionsLevel: [
        { value: undefined, label: "全部类别" },
        { value: "1", label: "公会" },
        { value: "2", label: "厅" }
      ],
      rules: {
        admin_account: [
          { required: true, message: "请输入管理员姓名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入管理员密码", trigger: "blur" }
        ],
        sociaty_no: [
          { required: true, message: "请输入厅的号码", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    // 获取本周一的时间戳
    let today = new Date().getDay();
    this.listQuery.end_at = this.getDate(new Date().getTime());
    this.listQuery.start_at = this.monday();
  },
  methods: {
    // 获取当前时间和本周第一天的时间
    getDate(data) {
      let date = new Date(data);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      let h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      let m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      let s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },

    monday() {
      let nowTemp = new Date(); //当前时间
      let oneDayLong = 24 * 60 * 60 * 1000; //一天的毫秒数
      let c_time = nowTemp.getTime(); //当前时间的毫秒时间
      let c_day = nowTemp.getDay() || 7; //当前时间的星期几
      let m_time = c_time - (c_day - 1) * oneDayLong; //当前周一的毫秒时间
      let monday = new Date(m_time); //设置周一时间对象
      let m_year = monday.getFullYear();
      let m_month = monday.getMonth() + 1;
      let m_date = monday.getDate();
      return m_year + "-" + m_month + "-" + m_date + " 00:00:00";
    },
    getList() {
      setTimeout(() => {
        this.listLoading = true;
        let urlData = "?";
        if (this.listQuery.pageNum) {
          urlData = urlData + `page=${this.listQuery.pageNum}&`;
        }
        if (this.listQuery.perPage) {
          urlData = urlData + `perPage=${this.listQuery.perPage}`;
        }
        // if(this.listQuery.relations){ urlData = urlData + `&relations=${this.listQuery.relations}`}
        if (this.listQuery.type) {
          urlData = urlData + `&type=${this.listQuery.type}`;
        }
        if (this.listQuery.start_at) {
          urlData = urlData + `&start_at=${this.listQuery.start_at}`;
        }
        if (this.listQuery.end_at) {
          urlData = urlData + `&end_at=${this.listQuery.end_at}`;
        }

        treeMenu(urlData).then(response => {
          this.menuList = response.data.list;
          this.total = response.data.meta.total;

          this.listLoading = false;
        });
      }, 100);
    },
    getList2() {
      this.listLoading = true;
      let urlData = `?user_id=${this.listQuery2.user_id}&`;
      if (this.listQuery2.pageNum) {
        urlData = urlData + `page=${this.listQuery2.pageNum}&`;
      }
      if (this.listQuery2.perPage) {
        urlData = urlData + `perPage=${this.listQuery2.perPage}`;
      }
      if (this.listQuery.start_at) {
        urlData = urlData + `&start_at=${this.listQuery.start_at}`;
      }
      if (this.listQuery.end_at) {
        urlData = urlData + `&end_at=${this.listQuery.end_at}`;
      }
      info(urlData).then(response => {
        this.menuList2 = response.data.list;
        this.total2 = response.data.meta.total;

        this.listLoading = false;
      });
    },
    getExcel() {
      let urlData = "?";
      if (this.listQuery.start_at) {
        urlData = urlData + `&start_at=${this.listQuery.start_at}`;
      }
      if (this.listQuery.end_at) {
        urlData = urlData + `&end_at=${this.listQuery.end_at}`;
      }
      if (this.listQuery.type) {
        urlData = urlData + `&type=${this.listQuery.type}`;
      }
      urlData = urlData === "?" ? "" : urlData;
      getExcel(urlData).then(response => {
        location.href = response.data.download_url;
      });
    },
    handleCreate(row) {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    handleUpdate(row) {
      // this.form = []
      // this.form.admin_account = row.admin_account
      //
      // this.dialogStatus = 'update'
      // this.dialogFormVisible = true
      //
      // let parentNode = this.findTreeNode(row.parentId)
      // if (parentNode) {
      //   this.form.parent_id = parentNode.menu_name
      // }
      //
      // this.form = Object.assign({}, this.form)
      this.listQuery2.user_id = row.user_id;
      this.getList2();
      this.isDetails = true;
    },
    handleDelete(row) {
      deleteMenu(row.sociaty_id).then(response => {
        if (response.code === 200) {
          this.getList();
          this.$notify({
            type: "success",
            message: "操作成功",
            position: "bottom-right",
            showClose: false,
            duration: 3000
          });
        } else {
          this.$message({
            message: response.message,
            type: "error"
          });
        }
      });
    },
    submitForm() {
      // this.form.parent_id = undefined;
      this.$refs["dataForm"].validate(valid => {
        let md5PW = md5(this.form.password);
        this.form.password = md5PW;
        if (valid && this.dialogStatus === "create") {
          saveMenu(this.form).then(response => {
            if (response.code === 200) {
              this.getList();
              this.$notify({
                type: "success",
                message: "操作成功",
                position: "bottom-right",
                showClose: false,
                duration: 3000
              });
              this.dialogFormVisible = false;
            } else {
              this.submitFail(123456);
              this.$message({
                message: response.message,
                type: "error"
              });
            }
          });
        } else if (valid && this.dialogStatus === "update") {
          updateMenu(this.form).then(response => {
            if (response.code === 200) {
              this.getList();
              this.$notify({
                type: "success",
                message: "操作成功",
                position: "bottom-right",
                showClose: false,
                duration: 3000
              });
              this.dialogFormVisible = false;
            } else {
              this.$message({
                message: response.message,
                type: "error"
              });
            }
          });
        }
      });
    },
    cache() {
      cacheMenu(this.form).then(response => {
        this.$notify({
          type: "success",
          message: "操作成功",
          position: "bottom-right",
          showClose: false,
          duration: 3000
        });
      });
    },
    findTreeNode(id) {
      let node = this._.find(this.menuList, { id: parseInt(id) });
      return node;
    },
    handleExpand() {
      this.expandAll = !this.expandAll;
      this.expandAllTitle = this.expandAll ? "折叠全部" : "展开全部";
    },
    resetForm() {
      this.form = {
        admin_account: undefined,
        password: undefined,
        sociaty_no: undefined
      };
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs["dataForm"]) {
        this.$refs["dataForm"].clearValidate(); // 清除整个表单的校验
      }
    },
    handleAvatarSuccess(res, file) {

    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }

      this.form.avatar = file;
      // return isJPG && isLt2M;
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.mb {
  margin-bottom: 10px;
}

.app-container /deep/ .el-date-editor.el-input {
  margin-bottom: 10px;
}

.app-container /deep/ .el-select {
  margin-bottom: 10px;
}
</style>
